//
// Created by 33145 on 2023/6/9.
//

#ifndef ROCKET_RPC_CHANNEL_H
#define ROCKET_RPC_CHANNEL_H

#include <google/protobuf/service.h>
#include <memory>

#include "../tcp/net_addr.h"
#include "../tcp/tcp_client.h"

namespace rocket {
class RPCChannel : public google::protobuf::RpcChannel, public std::enable_shared_from_this<RPCChannel> {
  public:
    typedef std::shared_ptr<RPCChannel> ptr;
    typedef std::shared_ptr<google::protobuf::RpcController> controller_ptr;
    typedef std::shared_ptr<google::protobuf::Closure> closure_ptr;
    typedef std::shared_ptr<google::protobuf::Message> message_ptr;

    explicit RPCChannel(NetAddr::ptr peer_addr);
    ~RPCChannel() override;

    void Init(const controller_ptr& controller, const message_ptr& req, const message_ptr& res, const closure_ptr& done);
    controller_ptr getController() { return _controller; }
    closure_ptr getClosure() { return _closure; }
    message_ptr getRequest() { return _request; }
    message_ptr getResponse() { return _response; }

    TCPClient::ptr getTCPClient();
    TimerEvent::ptr getTimerEvent();

    // 需要实现重写函数
    void CallMethod(const google::protobuf::MethodDescriptor* method,
                            google::protobuf::RpcController* controller, const google::protobuf::Message* request,
                            google::protobuf::Message* response, google::protobuf::Closure* done) override;

  private:
    NetAddr::ptr _local_addr {nullptr};
    NetAddr::ptr _peer_addr {nullptr};

    controller_ptr _controller {nullptr};
    closure_ptr _closure {nullptr};
    message_ptr _request {nullptr};
    message_ptr _response {nullptr};

    bool _is_init {false};

    TCPClient::ptr _client {nullptr};
    TimerEvent::ptr _timer_event {nullptr};
  };
}

#endif //ROCKET_RPC_CHANNEL_H
